<template>
  <div class="quick-order mx-auto py-4">
    <!-- 页面标题与导航 -->
    <div class="page-header mb-3">
      <div class="flex items-center text-gray-500 text-xs mb-1">
        <router-link to="/" class="hover:text-primary-600">首页</router-link>
        <span class="mx-2">/</span>
        <span class="text-gray-800">快速订货</span>
      </div>
      <div class="flex justify-between items-center">
        <h1 class="text-xl font-bold text-gray-800">快速订货</h1>
        <div class="flex items-center space-x-2">
 
          <el-button size="small" type="success">
            <el-icon><ShoppingCart /></el-icon>
            <span class="ml-1">查看购物车</span>
          </el-button>
        </div>
      </div>
    </div>

    <!-- 切换标签 -->
    <div class="order-tabs mb-2">
      <div class="bg-white rounded-lg shadow-sm overflow-hidden">
        <div class="border-b border-gray-200">
          <ul class="flex">
            <li class="flex-1">
              <button
                class="w-full py-2 px-4 text-sm text-center border-b-2"
                :class="currentMode === 'quick' ? 'border-primary-500 font-medium text-primary-600 bg-primary-50/50' : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'"
                type="button"
                @click="switchMode('quick')"
              >
                极速下单
              </button>
            </li>
            <li class="flex-1">
              <button
                class="w-full py-2 px-4 text-sm text-center border-b-2"
                :class="currentMode === 'traditional' ? 'border-primary-500 font-medium text-primary-600 bg-primary-50/50' : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'"
                type="button"
                @click="switchMode('traditional')"
              >
                传统模式
              </button>
            </li>
          </ul>
        </div>
      </div>
    </div>

    <!-- 快速下单区域 -->
    <div v-if="currentMode === 'quick'" class="order-container bg-white rounded-lg shadow-sm overflow-hidden">
      <!-- 商品搜索行 -->
      <div class="order-search-row bg-gray-50 px-2 py-1 border-b border-gray-200">
        <div class="flex items-center">
          <el-input
            v-model="searchQuery"
            placeholder="请输入商品助记码/商品编号/商品名称"
            clearable
            class="w-full"
            @keydown.down.prevent="selectNextProduct"
            @keydown.up.prevent="selectPrevProduct"
            @keydown.enter.prevent="searchProducts"
            ref="searchInput"
            :loading="loading"
          >
            <template #append>
              <el-button type="primary" @click="searchProducts" :loading="loading">
                <el-icon><Search /></el-icon>
              </el-button>
            </template>
          </el-input>
          <div class="ml-2 text-xs text-gray-500 hidden md:block">按↑↓键选择商品，回车确认</div>
        </div>
      </div>

      <!-- 商品搜索结果表 -->
      <div v-if="searchResults.length > 0" class="search-results-table compact-table border-b border-gray-200">
        <el-table
          :data="searchResults"
          style="width: 100%"
          size="small"
          :highlight-current-row="true"
          :current-row-key="selectedIndex"
          @row-click="(row: any) => selectedIndex = searchResults.indexOf(row)"
        >
          <el-table-column prop="title" label="商品名称" min-width="120" />
          <el-table-column prop="goodsSpec" label="规格" width="100" />
          <el-table-column prop="manufacturer" label="生产厂家" min-width="120" />
          <el-table-column prop="unit" label="单位" width="80" />
          <el-table-column prop="formula" label="剂型" width="80" />
          <el-table-column prop="price" label="售价" width="80">
            <template #default="{ row }">
              <div class="flex flex-col">
                <span class="text-red-600">{{ formatPriceAuth(row.price, !!userStore.token, userStore.userInfo?.discount, row.noDiscounts) }}</span>
                <span v-if="userStore.userInfo?.discount && row.noDiscounts !== 1" class="text-gray-400 text-xs line-through">
                  {{ formatPriceAuth(row.price, !!userStore.token) }}
                </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="库存" width="80">
            <template #default="{ row }">
              <span :class="getStockStatusClass(row.storNum)">{{ getStockStatusText(row.storNum) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="有效期至" width="100">
            <template #default="{ row }">
              <span v-if="row.nearestExpiredDate" class="text-xs text-orange-600">{{ formatDate(row.nearestExpiredDate) }}</span>
              <span v-else class="text-xs text-gray-400">-</span>
            </template>
          </el-table-column>
          <el-table-column label="包装信息" width="120">
            <template #default="{ row }">
              <div class="flex flex-col text-xs">
                <span v-if="row.midpack > 1" class="package-tag package-mid mb-1">
                  中包装 {{ row.midpack }}{{ row.unit }}
                </span>
                <span class="package-tag package-single mb-1">件包装 {{ Math.floor(row.qty) }}</span>

                <span v-if="row.midpack > 1" class="text-xs text-gray-600 mt-1">
                  <span v-if="row.isMidpackSaleDisabled === 1" class="no-split">不拆零</span>
                </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="数量" width="120">
            <template #default="{ row }">
              <el-input-number
                v-model="row.quantity"
                :min="getMinQuantity(row)"
                :max="Math.max(getMinQuantity(row), Math.min(1000, Number(row.storNum) || 1000))"
                :step="getQuantityStep(row)"
                size="small"
                :ref="(el:any) => { if(el) quantityInputs[searchResults.indexOf(row)] = el }"
                @change="() => addToCart(row)"
                @keydown.enter.prevent="addToCart(row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template #default="{ row }">
              <el-button
                type="primary"
                size="small"
                :disabled="parseFloat(row.storNum) <= 0 || !isValidQuantity(row) || addingToCartIds.has(row.goodsId)"
                :loading="addingToCartIds.has(row.goodsId)"
                @click="addToCart(row)"
              >{{ addingToCartIds.has(row.goodsId) ? '添加中...' : '添加' }}</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 空状态 -->
      <div v-else-if="!loading" class="empty-state py-8 flex flex-col items-center justify-center text-gray-400">
        <div class="empty-icon mb-2">
          <el-icon :size="32"><Search /></el-icon>
        </div>
        <p class="text-sm">请输入关键词搜索商品</p>
      </div>

      <!-- 加载状态 -->
      <div v-else class="loading-state py-8 flex flex-col items-center justify-center">
        <el-icon class="animate-spin" :size="32"><Loading /></el-icon>
        <p class="text-sm text-gray-500 mt-2">加载中...</p>
      </div>

      <!-- 已选商品列表 -->
      <div class="order-item-list compact-table">
        <div class="flex items-center justify-between bg-blue-50 px-2 py-1 border-b border-gray-200">
          <div class="text-sm font-medium text-gray-700">已选商品 ({{ orderItems.length }})</div>
          <div class="flex items-center space-x-2 text-xs">
            <el-checkbox v-model="selectAll" @change="toggleSelectAll" size="small">全选</el-checkbox>
            <button 
              class="text-red-600 hover:text-red-700 flex items-center" 
              type="button"
              @click="deleteSelected"
            >
              <el-icon class="mr-1"><Delete /></el-icon>删除
            </button>
            <button
              class="text-gray-600 hover:text-gray-700 flex items-center"
              type="button"
              @click="clearShoppingCart"
            >
              <el-icon class="mr-1"><Delete /></el-icon>清空
            </button>
          </div>
        </div>
        
        <div v-if="orderItems.length > 0">
          <el-table
            :data="orderItems"
            style="width: 100%"
            size="small"
          >
            <el-table-column width="50">
              <template #default="{ row }">
                <el-checkbox v-model="row.selected" @change="updateSelectedState" />
              </template>
            </el-table-column>
            <el-table-column prop="title" label="商品名称" min-width="120" />
            <el-table-column prop="goodsSpec" label="规格" width="100" />
            <el-table-column prop="manufacturer" label="生产厂家" min-width="120" />
            <el-table-column prop="unit" label="单位" width="80" />
            <el-table-column prop="formula" label="剂型" width="80" />
            <el-table-column prop="price" label="售价" width="80">
              <template #default="{ row }">
                <div class="flex flex-col">
                  <span class="text-red-600">{{ formatPriceAuth(row.price, !!userStore.token, userStore.userInfo?.discount, row.noDiscounts) }}</span>
                  <span v-if="userStore.userInfo?.discount && row.noDiscounts !== 1" class="text-gray-400 text-xs line-through">
                    {{ formatPriceAuth(row.price, !!userStore.token) }}
                  </span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="库存" width="80">
              <template #default="{ row }">
                <span :class="getStockStatusClass(row.storNum)">{{ getStockStatusText(row.storNum) }}</span>
              </template>
            </el-table-column>

            <el-table-column label="包装信息" width="120">
              <template #default="{ row }">
                <div class="flex flex-col text-xs">
                  <span v-if="row.midpack > 1" class="package-tag package-mid mb-1">
                    中包装 {{ row.midpack }}{{ row.unit }}
                  </span>
                  <span class="package-tag package-single mb-1">件包装 {{ Math.floor(row.qty) }}</span>

                  <span v-if="row.midpack > 1" class="text-xs text-gray-600 mt-1">
                    <span v-if="row.isMidpackSaleDisabled === 1" class="no-split">不拆零</span>
                  </span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="数量" width="120">
              <template #default="{ row }">
                <el-input-number
                  v-model="row.quantity"
                  :min="getMinQuantity(row)"
                  :max="Math.max(getMinQuantity(row), Math.min(1000, Number(row.storNum) || 1000))"
                  :step="getQuantityStep(row)"
                  size="small"
                  :disabled="parseFloat(row.storNum) <= 0"
                  @change="updateOrderTotal"
                />
              </template>
            </el-table-column>
            <el-table-column label="金额" width="100">
              <template #default="{ row }">
                <div class="flex flex-col">
                  <span class="font-medium">{{ formatPriceAuth((Number(row.price) * row.quantity), !!userStore.token, userStore.userInfo?.discount, row.noDiscounts) }}</span>
                  <span v-if="userStore.userInfo?.discount && row.noDiscounts !== 1" class="text-gray-400 text-xs line-through">
                    {{ formatPriceAuth((Number(row.price) * row.quantity), !!userStore.token) }}
                  </span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80">
              <template #default="{ $index }">
                <button
                  class="text-red-500 hover:text-red-700 text-xs"
                  type="button"
                  @click="removeItem($index)"
                >
                  删除
                </button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <!-- 空状态 -->
        <div v-else class="empty-state py-8 flex flex-col items-center justify-center text-gray-400">
          <div class="empty-icon mb-2">
            <el-icon :size="32"><ShoppingBag /></el-icon>
          </div>
          <p class="text-sm">购物车空空如也，请搜索并添加商品</p>
        </div>
      </div>

      <!-- 订单底部 -->
      <div class="order-footer bg-gray-50 px-4 py-2 flex items-center justify-between border-t border-gray-200">
        <div class="order-counts text-sm text-gray-600">
          已选择<span class="text-primary-600 font-medium mx-1">{{ selectedCount }}</span>个商品
        </div>
        <div class="order-total flex items-center">
          <div class="mr-4 text-sm flex flex-col items-end">
            <span v-if="userStore.userInfo?.discount" class="text-gray-400 text-xs line-through">
              原价: {{ formatPriceAuth(orderTotal, !!userStore.token) }}
            </span>
            <span>
              总价: <span class="text-red-600 font-bold">{{ formatPriceAuth(orderTotal, !!userStore.token, userStore.userInfo?.discount) }}</span>
            </span>
          </div>
          <el-button type="success" @click="submitOrder" :loading="isSubmittingOrder">
            提交订单
          </el-button>
        </div>
      </div>
    </div>

    <!-- 传统模式订单区域 -->
    <div v-if="currentMode === 'traditional'" class="order-container bg-white rounded-lg shadow-sm overflow-hidden">
      <!-- 搜索行 -->
      <div class="order-search-row bg-gray-50 px-3 py-2 border-b border-gray-200">
        <div class="flex items-center">
          <el-input
            v-model="searchQuery"
            placeholder="请输入商品名称/助记码/商品编号"
            clearable
            class="w-full max-w-xl"
            ref="searchInput"
            :loading="loading"
            @keyup.enter="loadProducts"
          >
            <template #append>
              <el-button type="primary" @click="loadProducts" :loading="loading">
                <el-icon><Search /></el-icon>
              </el-button>
            </template>
          </el-input>
        </div>
      </div>

      <!-- 商品表格 -->
      <div class="traditional-table">
        <el-table
          :data="allProducts"
          style="width: 100%"
          size="small"
          v-loading="loading"
        >
          <el-table-column prop="title" label="商品名称" min-width="120" />
          <el-table-column prop="goodsSpec" label="商品规格" min-width="120" />
          <el-table-column prop="manufacturer" label="生产厂家" min-width="120" />
          <el-table-column prop="unit" label="单位" width="80" />
          <el-table-column prop="formula" label="剂型" width="80" />
          <el-table-column prop="price" label="含税售价" width="100">
            <template #default="{ row }">
              <div class="flex flex-col">
                <span class="text-red-600">{{ formatPriceAuth(row.price, !!userStore.token, userStore.userInfo?.discount, row.noDiscounts) }}</span>
                <span v-if="userStore.userInfo?.discount && row.noDiscounts !== 1" class="text-gray-400 text-xs line-through">
                  {{ formatPriceAuth(row.price, !!userStore.token) }}
                </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="商品库存" width="100">
            <template #default="{ row }">
              <span :class="getStockStatusClass(row.storNum)">{{ getStockStatusText(row.storNum) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="approvalNo" label="批准文号" width="120" />
          <el-table-column label="有效期至" width="100">
            <template #default="{ row }">
              <span v-if="row.nearestExpiredDate" class="text-xs text-orange-600">{{ formatDate(row.nearestExpiredDate) }}</span>
              <span v-else class="text-xs text-gray-400">-</span>
            </template>
          </el-table-column>
          <el-table-column label="包装信息" width="120">
            <template #default="{ row }">
              <div class="flex flex-col text-xs">
                <span v-if="row.midpack > 1" class="package-tag package-mid mb-1">
                  中包装 {{ row.midpack }}{{ row.unit }}
                </span>
                <span class="package-tag package-single mb-1">件包装 {{ Math.floor(row.qty) }}</span>

                <span v-if="row.midpack > 1" class="text-xs text-gray-600 mt-1">
                  <span v-if="row.isMidpackSaleDisabled === 1" class="no-split">不拆零</span>
                </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="数量" width="120">
            <template #default="{ row }">
              <el-input-number
                v-model="row.quantity"
                :min="getMinQuantity(row)"
                :max="Math.max(getMinQuantity(row), Math.min(1000, Number(row.storNum) || 1000))"
                :step="getQuantityStep(row)"
                size="small"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template #default="{ row }">
              <el-button
                type="primary"
                size="small"
                icon="ShoppingCart"
                circle
                :disabled="parseFloat(row.storNum) <= 0 || !isValidQuantity(row) || addingToCartIds.has(row.goodsId)"
                :loading="addingToCartIds.has(row.goodsId)"
                @click="addToCart(row)"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 空状态 -->
      <div v-if="allProducts.length === 0 && !loading" class="empty-state py-10 flex flex-col items-center justify-center text-gray-400">
        <div class="empty-icon mb-3">
          <el-icon :size="40"><Search /></el-icon>
        </div>
        <p class="text-base">未找到符合条件的商品</p>
      </div>

      <!-- 分页 -->
      <div class="pagination py-3 flex justify-center border-t border-gray-200 mt-auto">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          background
          small
          @size-change="loadProducts"
          @current-change="loadProducts"
        />
      </div>

      <!-- 已选商品与提交订单 -->
      <div class="order-footer bg-gray-50 px-4 py-3 flex items-center justify-between border-t border-gray-200">
        <div class="selected-info">
          <span class="text-sm text-gray-600">已选择 <span class="text-primary-600 font-medium">{{ selectedCount }}</span> 个商品</span>
          <span class="text-sm text-gray-600 ml-4">总金额：<span class="text-red-600 font-bold">{{ formatPriceAuth(orderTotal, !!userStore.token, userStore.userInfo?.discount) }}</span></span>
        </div>
        <div class="action-buttons flex space-x-3">
          <el-button type="default" size="default" @click="clearShoppingCart" :loading="loading">清空</el-button>
          <el-button type="primary" size="default" @click="submitOrder" :loading="isSubmittingOrder">提交订单</el-button>
        </div>
      </div>
    </div>

    <!-- 快捷键帮助 (仅在极速下单模式下显示) -->
    <div v-if="currentMode === 'quick'" class="keyboard-shortcuts mt-2 bg-white rounded-lg shadow-sm p-3">
      <div class="text-sm font-medium text-gray-700 mb-2">快捷键指南:</div>
      <div class="grid grid-cols-2 md:grid-cols-4 gap-2 text-xs text-gray-600">
        <div class="flex items-center"><kbd class="px-2 py-1 bg-gray-100 rounded mr-2">↑/↓</kbd> 浏览搜索结果</div>
        <div class="flex items-center"><kbd class="px-2 py-1 bg-gray-100 rounded mr-2">Enter</kbd> 选中并跳转到数量</div>
        <div class="flex items-center"><kbd class="px-2 py-1 bg-gray-100 rounded mr-2">Tab</kbd> 切换输入焦点</div>
        <div class="flex items-center"><kbd class="px-2 py-1 bg-gray-100 rounded mr-2">Ctrl+S</kbd> 提交订单</div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Delete, ShoppingBag, ShoppingCart, Loading } from '@element-plus/icons-vue'
import { getGoodsList } from '@/api/modules/goods'
import type { Goods } from '@/api/modules/goods'
import { useCartStore } from '@/stores/cart'
import { useUserStore } from '@/stores/user'
import { getStockStatusText, getStockStatusClass } from '@/lib/stockUtils'
import { formatPriceAuth } from '@/lib/utils'

// 获取购物车 store
const cartStore = useCartStore()
const userStore = useUserStore()

// 格式化日期函数
function formatDate(dateString: string): string {
  if (!dateString) return ''
  
  try {
    const date = new Date(dateString)
    if (isNaN(date.getTime())) return dateString
    
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    
    return `${year}-${month}-${day}`
  } catch (error) {
    return dateString
  }
}

// 当前模式 (极速下单/传统模式)
const currentMode = ref<'quick' | 'traditional'>('quick')

// 搜索查询
const searchQuery = ref('')
const searchInput = ref<HTMLElement | null>(null)
const selectedIndex = ref(-1)
const quantityInputs = ref<Record<number, any>>({})

// 分页参数
const pagination = ref({
  page: 1,
  size: 20,
  total: 0
})

// 加载状态
const loading = ref(false)

// Add to cart loading states
const addingToCartIds = ref<Set<string>>(new Set())

// 订单商品
interface OrderItem extends Goods {
  quantity: number
  selected: boolean
}

// 搜索结果
const searchResults = ref<OrderItem[]>([])

// 所有商品列表 (传统模式使用)
const allProducts = ref<OrderItem[]>([])

// 已选商品列表
const orderItems = ref<OrderItem[]>([])

// 全选状态
const selectAll = ref(true)

// 计算选中的商品数量
const selectedCount = computed(() => {
  return orderItems.value.filter(item => item.selected).length
})

// 计算订单总价
const orderTotal = ref(0)

// 更新订单总价
function updateOrderTotal() {
  orderTotal.value = orderItems.value
    .filter(item => item.selected)
    .reduce((total, item) => {
      const price = Number(item.price)
      const quantity = item.quantity
      if (userStore.userInfo?.discount && item.noDiscounts !== 1) {
        return total + price * userStore.userInfo.discount * quantity
      }
      return total + price * quantity
    }, 0)
}

// 切换订单模式
function switchMode(mode: 'quick' | 'traditional') {
  currentMode.value = mode
  searchQuery.value = ''
  selectedIndex.value = -1
  
  if (mode === 'traditional') {
    loadProducts()
  }
  
  nextTick(() => {
    if (searchInput.value) {
      (searchInput.value as HTMLElement).focus()
    }
  })
}

// 加载商品列表
async function loadProducts() {
  try {
    loading.value = true
    const params = {
      page: pagination.value.page,
      size: pagination.value.size,
      keyWord: searchQuery.value.toLocaleUpperCase()
    }
    const response: any = await getGoodsList(params)
    allProducts.value = response.data.list.map((item: Goods) => ({
      ...item,
      quantity: item.midpack > 1 && item.isMidpackSaleDisabled === 1 ? item.midpack : 1,
      selected: false
    }))
    pagination.value.total = response.data.pagination.total
  } catch (error) {
    ElMessage.error('加载商品列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索产品
async function searchProducts() {
  if (!searchQuery.value.trim()) {
    ElMessage.warning('请输入搜索关键词')
    return
  }
  
  try {
    loading.value = true
    const params = {
      page: 1,
      size: 20,
      keyWord: searchQuery.value.toUpperCase()
    }
    const response: any = await getGoodsList(params)
    searchResults.value = response.data.list.map((item: Goods) => ({
      ...item,
      quantity: item.midpack > 1 && item.isMidpackSaleDisabled === 1 ? item.midpack : 1,
      selected: false
    }))
    selectedIndex.value = -1
  } catch (error) {
    ElMessage.error('搜索失败')
  } finally {
    loading.value = false
  }
}

// 选择下一个产品 (向下箭头)
function selectNextProduct() {
  if (searchResults.value.length === 0) return
  
  if (selectedIndex.value < searchResults.value.length - 1) {
    selectedIndex.value++
  } else {
    selectedIndex.value = 0
  }
}

// 选择上一个产品 (向上箭头)
function selectPrevProduct() {
  if (searchResults.value.length === 0) return
  
  if (selectedIndex.value > 0) {
    selectedIndex.value--
  } else {
    selectedIndex.value = searchResults.value.length - 1
  }
}

// 聚焦到数量输入框 (Enter键)
// function focusQuantity() {
//   if (selectedIndex.value >= 0 && selectedIndex.value < searchResults.value.length) {
//     nextTick(() => {
//       const input = quantityInputs.value[selectedIndex.value]
//       if (input && input.$el) {
//         const inputEl = input.$el.querySelector('input')
//         if (inputEl instanceof HTMLInputElement) {
//           inputEl.focus()
//           inputEl.select()
//         }
//       }
//     })
//   }
// }

// 加载购物车数据
async function loadCartData() {
  try {
    await cartStore.fetchCartList()
    orderItems.value = cartStore.cartItems.map((item: any) => ({
      ...item.goodsInfo,
      quantity: item.count,
      selected: true,
      id: item.id // 使用cartItem.id
    })) as OrderItem[]
    updateOrderTotal()
  } catch (error) {
    ElMessage.error('加载购物车数据失败')
  }
}

// 获取最小数量
function getMinQuantity(product: any): number {
  // 如果是中包装且不支持拆零，最小数量为midpack
  if (product.midpack > 1 && product.isMidpackSaleDisabled === 1) {
    return product.midpack
  }
  return 1
}

// 获取数量步长
function getQuantityStep(product: any): number {
  // 如果是中包装且不支持拆零，步长为midpack
  if (product.midpack > 1 && product.isMidpackSaleDisabled === 1) {
    return product.midpack
  }
  return 1
}

// 验证数量是否有效
function isValidQuantity(product: any): boolean {
  // 如果是中包装且不支持拆零，数量必须是midpack的倍数
  if (product.midpack > 1 && product.isMidpackSaleDisabled === 1) {
    return product.quantity % product.midpack === 0
  }
  return true
}

// 添加到购物车
async function addToCart(item: OrderItem) {
  // Prevent multiple clicks
  if (addingToCartIds.value.has(item.goodsId)) {
    return;
  }

  try {
    // Check stock before adding to cart
    if (parseFloat(item.storNum) <= 0) {
      ElMessage.warning(`商品 ${item.title} 库存不足`);
      return;
    }
    
    // 验证数量是否有效
    if (!isValidQuantity(item)) {
      ElMessage.warning(`该商品不支持拆零，数量必须是${item.midpack}的倍数`);
      // 自动调整为最近的有效数量
      item.quantity = Math.max(getMinQuantity(item), Math.round(item.quantity / item.midpack) * item.midpack);
      return;
    }
    
    // Set loading state
    addingToCartIds.value.add(item.goodsId);
    
    const success = await cartStore.addItemToCart(item.goodsId, item.quantity)
    if (success) {
      const packingInfo = item.midpack > 1 && item.isMidpackSaleDisabled === 1 
        ? `（按${item.midpack}${item.unit}计）` 
        : '';
      ElMessage.success(`已添加 ${item.title} ${packingInfo}到购物车`)
      await loadCartData() // 添加后重新拉取购物车
      // 重置搜索结果中的数量为最小有效数量
      item.quantity = getMinQuantity(item)
      // 重新聚焦搜索框
      if (searchInput.value) {
        (searchInput.value as HTMLElement).focus()
      }
    }
  } catch (error) {
    ElMessage.error('添加购物车失败')
  } finally {
    // Always remove from loading state
    addingToCartIds.value.delete(item.goodsId);
  }
}

// 切换全选
function toggleSelectAll(val: boolean) {
  orderItems.value.forEach(item => {
    item.selected = val
  })
  updateOrderTotal()
}

// 更新选中状态
function updateSelectedState() {
  const allSelected = orderItems.value.every(item => item.selected)
  selectAll.value = allSelected
  updateOrderTotal()
}

// 删除选中商品
async function deleteSelected() {
  if (selectedCount.value === 0) {
    ElMessage.warning('请先选择要删除的商品')
    return
  }
  
  try {
    const selectedItems = orderItems.value.filter(item => item.selected)
    const success = await Promise.all(selectedItems.map(item => cartStore.removeItem(item.id)))
    
    if (success.every(Boolean)) {
      orderItems.value = orderItems.value.filter(item => !item.selected)
      updateOrderTotal()
      ElMessage.success('已删除选中商品')
    }
  } catch (error) {
    ElMessage.error('删除商品失败')
  }
}

// 清空购物车
async function clearShoppingCart() {
  if (orderItems.value.length === 0) {
    ElMessage.warning('购物车已经是空的')
    return
  }
  
  try {
    const success = await cartStore.clearCartItems()
    if (success) {
      orderItems.value = []
      updateOrderTotal()
      ElMessage.success('已清空购物车')
    }
  } catch (error) {
    ElMessage.error('清空购物车失败')
  }
}

// 删除单个商品
async function removeItem(index: number) {
  try {
    const item = orderItems.value[index]
    const success = await cartStore.removeItem(item.id)
    if (success) {
      orderItems.value.splice(index, 1)
      updateSelectedState()
      ElMessage.success('已删除商品')
    }
  } catch (error) {
    ElMessage.error('删除商品失败')
  }
}

// 提交订单状态
const isSubmittingOrder = ref(false)

// 提交订单
async function submitOrder() {
  if (orderItems.value.length === 0) {
    ElMessage.warning('请先添加商品')
    return
  }
  if (selectedCount.value === 0) {
    ElMessage.warning('请选择要购买的商品')
    return
  }
  
  if (isSubmittingOrder.value) {
    return
  }
  
  isSubmittingOrder.value = true
  
  try {
    const selectedItems = orderItems.value.filter(item => item.selected)
    const success = await cartStore.createOrderFromCart(selectedItems.map(item => item.id)) // 传cartItem.id
    if (success) {
      ElMessage.success('订单提交成功!')
      // 清空已提交的商品
      await loadCartData() // 重新拉取购物车
      updateOrderTotal()
    }
  } catch (error) {
    ElMessage.error('提交订单失败')
  } finally {
    isSubmittingOrder.value = false
  }
}

// 监听键盘快捷键
function setupKeyboardShortcuts() {
  window.addEventListener('keydown', (e) => {
    // Ctrl+S 提交订单
    if (e.ctrlKey && e.key === 's') {
      e.preventDefault()
      submitOrder()
    }
  })
}

// 初始化
onMounted(async () => {
  try {
    await loadCartData()
    
    // 加载商品列表（传统模式）
    if (currentMode.value === 'traditional') {
      await loadProducts()
    }
    
    setupKeyboardShortcuts()
    // 自动聚焦搜索框
    if (searchInput.value) {
      (searchInput.value as HTMLElement).focus()
    }
  } catch (error) {
    ElMessage.error('初始化数据失败')
  }
})
</script>

<style scoped>
/* 紧凑表格样式 */
.compact-table th,
.compact-table td,
.traditional-table th,
.traditional-table td {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.compact-table :deep(.el-input-number),
.traditional-table :deep(.el-input-number) {
  width: 90px;
}

.compact-table :deep(.el-input-number.is-controls-right .el-input-number__decrease),
.compact-table :deep(.el-input-number.is-controls-right .el-input-number__increase),
.traditional-table :deep(.el-input-number.is-controls-right .el-input-number__decrease),
.traditional-table :deep(.el-input-number.is-controls-right .el-input-number__increase) {
  width: 18px;
}

.compact-table :deep(.el-button--small),
.traditional-table :deep(.el-button--small) {
  padding: 4px 8px;
  font-size: 12px;
}

.compact-table :deep(.el-checkbox__label),
.traditional-table :deep(.el-checkbox__label) {
  font-size: 12px;
  padding-left: 4px;
}

.traditional-table :deep(.el-button--small) {
  min-height: 24px;
  padding: 3px;
}

kbd {
  font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  font-size: 0.75rem;
  line-height: 1;
}

/* 自定义样式变量 */
:root {
  --primary-50: #e6f7ff;
  --primary-100: #bae7ff;
  --primary-200: #91d5ff;
  --primary-300: #69c0ff;
  --primary-400: #40a9ff;
  --primary-500: #1890ff;
  --primary-600: #096dd9;
  --primary-700: #0050b3;
  --primary-800: #003a8c;
  --primary-900: #002766;
}

.from-primary-500 {
  --tw-gradient-from: var(--primary-500);
  --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to, rgba(24, 144, 255, 0));
}

.to-primary-600 {
  --tw-gradient-to: var(--primary-600);
}

.bg-primary-50\/50 {
  background-color: rgba(230, 247, 255, 0.5);
}

.text-primary-600 {
  color: var(--primary-600);
}

.text-primary-700 {
  color: var(--primary-700);
}

.border-primary-500 {
  border-color: var(--primary-500);
}

.hover\:text-primary-700:hover {
  color: var(--primary-700);
}

/* 标签样式 - 紧凑设计 */
.prescription-tag {
  display: inline-block;
  padding: 2px 6px;
  background: linear-gradient(135deg, #dc2626, #b91c1c);
  color: white;
  font-size: 10px;
  font-weight: 500;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(220, 38, 38, 0.3);
}

.package-tag {
  display: inline-block;
  padding: 2px 6px;
  color: white;
  font-size: 10px;
  font-weight: 500;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.package-mid {
  background: linear-gradient(135deg, #059669, #10b981);
}

.package-single {
  background: linear-gradient(135deg, #3b82f6, #2563eb);
}

/* 包装信息 */
.no-split {
  color: #f59e0b;
  font-weight: 600;
  margin-left: 4px;
}
</style> 